package com.rolerealm.common.exception;

import com.rolerealm.common.constant.ErrorCode;
import com.rolerealm.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.Set;
import java.util.UUID;

/**
 * 全局异常处理器
 * 统一处理系统中的各种异常，返回标准化的错误响应
 * 
 * @author RoleRealm Team
 * @version 1.0.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     * 
     * @param e 业务异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleBaseException(BaseException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        logger.warn("业务异常 - TraceId: {}, ErrorCode: {}, Message: {}, Detail: {}, URI: {}", 
                traceId, e.getErrorCode().getCode(), e.getMessage(), e.getDetail(), request.getRequestURI());
        
        Result<Void> result = Result.error(e.getErrorCode());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理参数校验异常（@Valid）
     * 
     * @param e 参数校验异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        StringBuilder errorMsg = new StringBuilder("参数校验失败: ");
        
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(" ").append(fieldError.getDefaultMessage()).append("; ");
        }
        
        logger.warn("参数校验异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg.toString(), request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_INVALID);
        result.setMessage(errorMsg.toString());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理参数绑定异常
     * 
     * @param e 参数绑定异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        StringBuilder errorMsg = new StringBuilder("参数绑定失败: ");
        
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(" ").append(fieldError.getDefaultMessage()).append("; ");
        }
        
        logger.warn("参数绑定异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg.toString(), request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_ERROR);
        result.setMessage(errorMsg.toString());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理约束违反异常
     * 
     * @param e 约束违反异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        StringBuilder errorMsg = new StringBuilder("约束违反: ");
        
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            errorMsg.append(violation.getPropertyPath()).append(" ").append(violation.getMessage()).append("; ");
        }
        
        logger.warn("约束违反异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg.toString(), request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_INVALID);
        result.setMessage(errorMsg.toString());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理缺少请求参数异常
     * 
     * @param e 缺少请求参数异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "缺少必需参数: " + e.getParameterName() + " (" + e.getParameterType() + ")";
        
        logger.warn("缺少请求参数异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_MISSING);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理方法参数类型不匹配异常
     * 
     * @param e 方法参数类型不匹配异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "参数类型不匹配: " + e.getName() + " 期望类型 " + e.getRequiredType().getSimpleName() + "，实际值: " + e.getValue();
        
        logger.warn("参数类型不匹配异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_INVALID);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理HTTP消息不可读异常
     * 
     * @param e HTTP消息不可读异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "请求体格式错误: " + e.getMessage();
        
        logger.warn("HTTP消息不可读异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_ERROR);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理HTTP请求方法不支持异常
     * 
     * @param e HTTP请求方法不支持异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result<Void> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "请求方法不支持: " + e.getMethod() + "，支持的方法: " + String.join(", ", e.getSupportedMethods());
        
        logger.warn("HTTP请求方法不支持异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.REQUEST_METHOD_NOT_SUPPORTED);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理HTTP媒体类型不支持异常
     * 
     * @param e HTTP媒体类型不支持异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public Result<Void> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "媒体类型不支持: " + e.getContentType() + "，支持的媒体类型: " + String.join(", ", e.getSupportedMediaTypes().toString());
        
        logger.warn("HTTP媒体类型不支持异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.REQUEST_MEDIA_TYPE_NOT_SUPPORTED);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理404异常
     * 
     * @param e 404异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<Void> handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        String errorMsg = "请求的资源不存在: " + e.getRequestURL();
        
        logger.warn("404异常 - TraceId: {}, Message: {}, URI: {}", traceId, errorMsg, request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.NOT_FOUND);
        result.setMessage(errorMsg);
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理非法参数异常
     * 
     * @param e 非法参数异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        
        logger.warn("非法参数异常 - TraceId: {}, Message: {}, URI: {}", traceId, e.getMessage(), request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.PARAM_INVALID);
        result.setMessage(e.getMessage());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理非法状态异常
     * 
     * @param e 非法状态异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleIllegalStateException(IllegalStateException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        
        logger.warn("非法状态异常 - TraceId: {}, Message: {}, URI: {}", traceId, e.getMessage(), request.getRequestURI());
        
        Result<Void> result = Result.error(ErrorCode.SYSTEM_ERROR);
        result.setMessage(e.getMessage());
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理空指针异常
     * 
     * @param e 空指针异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        
        logger.error("空指针异常 - TraceId: {}, Message: {}, URI: {}", traceId, e.getMessage(), request.getRequestURI(), e);
        
        Result<Void> result = Result.error(ErrorCode.SYSTEM_ERROR);
        result.setMessage("系统内部错误，请联系管理员");
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理运行时异常
     * 
     * @param e 运行时异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String traceId = generateTraceId();
        
        logger.error("运行时异常 - TraceId: {}, Message: {}, URI: {}", traceId, e.getMessage(), request.getRequestURI(), e);
        
        Result<Void> result = Result.error(ErrorCode.SYSTEM_ERROR);
        result.setMessage("系统内部错误，请联系管理员");
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 处理其他异常
     * 
     * @param e 异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        String traceId = generateTraceId();
        
        logger.error("未知异常 - TraceId: {}, Message: {}, URI: {}", traceId, e.getMessage(), request.getRequestURI(), e);
        
        Result<Void> result = Result.error(ErrorCode.SYSTEM_ERROR);
        result.setMessage("系统内部错误，请联系管理员");
        result.setTraceId(traceId);
        return result;
    }

    /**
     * 生成追踪ID
     * 
     * @return 追踪ID
     */
    private String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}
